package com.tr.rentcar.controller.loginandregister;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;

import com.tr.rentcar.model.bean.User;
import com.tr.rentcar.model.dao.UserDao;
import com.tr.rentcar.model.dao.UserJfDao;

/**
 * Servlet implementation class register 注册
 */
@WebServlet("/register")
public class RegisterController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserDao udao = new UserDao();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if (request.getSession().getAttribute("userinfo") != null) {
			response.sendRedirect(request.getContextPath() + "/home");
			return;
		}
		request.getRequestDispatcher("WEB-INF/jsp/register.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		response.setContentType("text/html;charset=UTF-8");
		String tel = request.getParameter("tel");
		String one = DigestUtils.md5Hex(request.getParameter("upasswordone"));//对密码进行加密
		String uemail = request.getParameter("uemail");
		String uname = request.getParameter("uname");

		try {
			if (udao.save(tel, uname, uemail, one)) {
				// 存入登录信息
				User user = udao.findByTel(tel);
				session.setAttribute("userinfo", user);
				udao.xiugai(100, user.getUid());//赠送100积分
				new UserJfDao().pingjia(100, "新用户注册", user.getUid());//添加一条积分记录
				// 转到首页
				response.sendRedirect(request.getContextPath() + "/home");
				return;
			}else{
				request.getRequestDispatcher("WEB-INF/jsp/error.jsp").forward(request, response);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			request.setAttribute("reset", "注册失败！");
			doGet(request, response);
		}
	}

}
